package great.project;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
//@Component
public class SpringTransactionUtils {

//    @Resource
    private PlatformTransactionManager txManager;

    /**
     * 使用 事务执行
     *
     * @param function 过程并返回 结果
     * @param <T>      返回结果
     * @return 结果
     */
    public <T> T ofTransaction(Function<TransactionStatus, T> function) {
        T apply = null;
        final TransactionStatus transaction = txManager.getTransaction(new DefaultTransactionDefinition());
        try {
            apply = function.apply(transaction);
            txManager.commit(transaction);
        } catch (Exception e) {
            // 判断当前事务是否已经回滚了 如果没有 被回滚掉 则回滚
            final boolean rollbackOnly = transaction.isRollbackOnly();
            if (!rollbackOnly) {
                transaction.setRollbackOnly();
            }
            log.error("SpringTransactionUtils Exception", e);
        }
        return apply;

    }


    /**
     * 无返回值类型
     *
     * @param consumer 消费
     */
    public void ofTransaction(Consumer<TransactionStatus> consumer) {

        final TransactionStatus transaction = txManager.getTransaction(new DefaultTransactionDefinition());

        try {
            consumer.accept(transaction);
            txManager.commit(transaction);
        } catch (Exception e) {
            // 判断当前事务是否已经回滚了 如果没有 被回滚掉 则回滚
            final boolean rollbackOnly = transaction.isRollbackOnly();
            if (!rollbackOnly) {
                transaction.setRollbackOnly();
            }
            log.error("SpringTransactionUtils Exception", e);
        }


    }

    public void ofTransaction1(Consumer<TransactionStatus> consumer) {

        final TransactionStatus transaction = txManager.getTransaction(new DefaultTransactionDefinition());

        try {
            consumer.accept(transaction);
            txManager.commit(transaction);
        } catch (Exception e) {
            // 判断当前事务是否已经回滚了 如果没有 被回滚掉 则回滚
            final boolean rollbackOnly = transaction.isRollbackOnly();
            if (!rollbackOnly) {
                transaction.setRollbackOnly();
            }
            log.error("SpringTransactionUtils Exception", e);
        }


    }

    public void test1(TransactionStatus transactionStatus) {

    }

    public void test() {

        final Integer integer = ofTransaction((transactionStatus) -> {
            transactionStatus.setRollbackOnly();
            test1(transactionStatus);
            return 1;
        });



        ofTransaction(this::test1);

    }


}
